<?php
class ModelAccountCustomer extends Model {

    public function addCustomer($data, $customer_group_info) {

        $data['fax'] = (isset($data['fax']) ? $data['fax'] :  '');

        $salt = substr(md5(uniqid(rand(), true)), 0, 9);
        $password = sha1($salt . sha1($salt . sha1($data['password'])));

        $customer_query = $this->pdo->prepare("INSERT INTO " . $this->db_prefix . "customer SET 
            store_id          = :store_id,
            firstname         = :firstname,
            lastname          = :lastname, 
            email             = :email, 
            telephone         = :telephone, 
            fax               = :fax, 
            salt              = :salt, 
            password          = :password, 
            newsletter        = :newsletter,
            user_group_id = :user_group_id, 
            ip                = :ip, 
            status            = '1', 
            approved          = :approved, 
            date_added        = NOW()
            ");

        try{ 
            $customer_query->execute(array(
                ':store_id'   => (int)$this->site_id, 
                ':firstname'  => $data['firstname'], 
                ':lastname'   => $data['lastname'], 
                ':email'      => $data['email'], 
                ':telephone'  => $data['telephone'], 
                ':fax'        => $data['fax'], 
                ':salt'       => $salt,
                ':password'   => $password,
                ':newsletter' => (isset($data['newsletter']) ? (int)$data['newsletter'] : 0),
                ':user_group_id' => $customer_group_info['user_group_id'],
                ':ip'         => $this->request->server['REMOTE_ADDR'], 
                ':approved'   => (int)!$customer_group_info['approval'], 
            ));
        } catch (PDOException $e){
            trigger_error($e->getMessage());
        }

        $customer = $this->pdo->prepare("SELECT * FROM " . $this->db_prefix . "customer WHERE 
            salt = :salt 
            AND password =:password");

        $customer->execute(array(
            ':salt'       => $salt,
            ':password'   => $password,
        ));

        $customer_data = $customer->fetch(PDO::FETCH_ASSOC);

        $user_id = $customer_data['user_id'];

        $address = $this->pdo->prepare("INSERT INTO " . $this->db_prefix . "address SET 
            user_id     = :user_id, 
            firstname       = :firstname, 
            lastname        = :lastname, 
            company         = :company, 
            company_id      = :company_id, 
            tax_id          = :tax_id, 
            address_1       = :address_1, 
            address_2       = :address_2, 
            city            = :city, 
            postcode        = :postcode, 
            country_id      = :country_id, 
            zone_id         = :zone_id");

        $address->execute(array(
            ':user_id'  => (int)$user_id, 
            ':firstname'    => $customer_data['firstname'], 
            ':lastname'     => $customer_data['lastname'], 
            ':company'      => $data['company'], 
            ':company_id'   => $data['company_id'], 
            ':tax_id'       => $data['tax_id'], 
            ':address_1'    => $data['address_1'], 
            ':address_2'    => $data['address_2'], 
            ':city'         => $data['city'], 
            ':postcode'     => $data['postcode'], 
            ':country_id'   => (int)$data['country_id'], 
            ':zone_id'      => (int)$data['zone_id']
        ));

        // User is registering so there is only one
        // address for him at this point
        $address = $this->pdo->prepare("SELECT * FROM " . $this->db_prefix . "address 
            WHERE user_id = :user_id");

        $address->execute(array(':user_id' => $user_id));

        $address_data = $address->fetch(PDO::FETCH_ASSOC);
        $address_id = $address_data['address_id'];

        $address = $this->pdo->prepare("UPDATE " . $this->db_prefix . "customer 
            SET address_id = :address_id  
            WHERE user_id = :user_id");

        $address->execute(array(
            ':address_id'   => (int)$address_id,
            ':user_id'  => (int)$user_id
        ));

        return true;
    }

    public function editCustomer($data) {
        $this->db->query("UPDATE " . $this->db_prefix . "customer SET firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "' WHERE user_id = '" . (int)$this->customer->get_id() . "'");
    }

    public function editPassword($email, $password) {
        $this->db->query("UPDATE " . $this->db_prefix . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "' WHERE LOWER(email) = '" . $this->db->escape(mb_strtolower($email)) . "'");
    }

    public function editNewsletter($newsletter) {
        $this->db->query("UPDATE " . $this->db_prefix . "customer SET newsletter = '" . (int)$newsletter . "' WHERE user_id = '" . (int)$this->customer->get_id() . "'");
    }

    public function getCustomer($user_id) {
        $query = $this->db->query("SELECT * FROM " . $this->db_prefix . "customer WHERE user_id = '" . (int)$user_id . "'");

        return $query->row;
    }

    public function getCustomerByEmail($email) {
        $query = $this->db->query("SELECT * FROM " . $this->db_prefix . "customer WHERE LOWER(email) = '" . $this->db->escape(mb_strtolower($email)) . "'");

        return $query->row;
    }

    public function getCustomerByToken($token) {
        $query = $this->db->query("SELECT * FROM " . $this->db_prefix . "customer WHERE token = '" . $this->db->escape($token) . "' AND token != ''");

        $this->db->query("UPDATE " . $this->db_prefix . "customer SET token = ''");

        return $query->row;
    }

    public function getCustomers($data = array()) {
        $sql = "SELECT *, CONCAT(c.firstname, ' ', c.lastname) AS name, cg.name AS customer_group FROM " . $this->db_prefix . "customer c LEFT JOIN " . $this->db_prefix . "customer_group cg ON (c.user_group_id = cg.user_group_id) ";

        $implode = array();

        if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
            $implode[] = "LCASE(CONCAT(c.firstname, ' ', c.lastname)) LIKE '" . $this->db->escape(mb_strtolower($data['filter_name'])) . "%'";
        }

        if (isset($data['filter_email']) && !is_null($data['filter_email'])) {
            $implode[] = "LCASE(c.email) = '" . $this->db->escape(mb_strtolower($data['filter_email'])) . "'";
        }

        if (isset($data['filter_user_group_id']) && !is_null($data['filter_user_group_id'])) {
            $implode[] = "cg.user_group_id = '" . $this->db->escape($data['filter_user_group_id']) . "'";
        }	

        if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
            $implode[] = "c.status = '" . (int)$data['filter_status'] . "'";
        }	

        if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
            $implode[] = "c.approved = '" . (int)$data['filter_approved'] . "'";
        }	

        if (isset($data['filter_ip']) && !is_null($data['filter_ip'])) {
            $implode[] = "c.user_id IN (SELECT user_id FROM " . $this->db_prefix . "customer_ip WHERE ip = '" . $this->db->escape($data['filter_ip']) . "')";
        }	

        if (isset($data['filter_date_added']) && !is_null($data['filter_date_added'])) {
            $implode[] = "DATE(c.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
        }

        if ($implode) {
            $sql .= " WHERE " . implode(" AND ", $implode);
        }

        $sort_data = array(
            'name',
            'c.email',
            'customer_group',
            'c.status',
            'c.ip',
            'c.date_added'
        );	

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];	
        } else {
            $sql .= " ORDER BY name";	
        }

        if (isset($data['order']) && ($data['order'] == 'DESC')) {
            $sql .= " DESC";
        } else {
            $sql .= " ASC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }			

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }	

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }		

        $query = $this->db->query($sql);

        return $query->rows;	
    }

    public function getTotalCustomersByEmail($email) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . $this->db_prefix . "customer WHERE LOWER(email) = '" . $this->db->escape(mb_strtolower($email)) . "'");

        return $query->row['total'];
    }

    public function getIps($user_id) {
        $query = $this->db->query("SELECT * FROM `" . $this->db_prefix . "customer_ip` WHERE user_id = '" . (int)$user_id . "'");

        return $query->rows;
    }	

    public function isBanIp($ip) {
        $query = $this->db->query("SELECT * FROM `" . $this->db_prefix . "customer_ban_ip` WHERE ip = '" . $this->db->escape($ip) . "'");

        return $query->num_rows;
    }	
}
?>
